//
//  SCRNManager+Share.m
//  Shuaicheyeguan
//
//  Created by xiangtao on 2025/5/29.
//

#import "SCRNManager+Share.h"
#import "SCSharePickerVC.h"
#import "Config.h"
#import "NSString+Helper.h"
#import "UIImage+Utility.h"
#import "WXApi.h"
#import "WWKApi.h"

@implementation SCRNManager (Share)

//微信是否安装
RCT_EXPORT_METHOD(isWxAppInstall:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    BOOL isInstall = [WXApi isWXAppInstalled];
    callback(@[[NSNull null], @{@"isWxAppInstall": @(isInstall)}]);
  });
}

//企业微信是否安装
RCT_EXPORT_METHOD(isWxWorkAppInstall:(NSDictionary *)parameters callback:(RCTResponseSenderBlock)callback)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    BOOL isInstall = [WWKApi isAppInstalled];
    callback(@[[NSNull null], @{@"isWxWorkAppInstall": @(isInstall)}]);
  });
}

//车辆详情多图分享
RCT_EXPORT_METHOD(sharePlatFormCarDetailImages:(NSDictionary *)car)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
      NSMutableDictionary *mParams = [NSMutableDictionary dictionaryWithCapacity:0];
      [mParams setValue:@([Config sharedConfig].user.merchantId) forKey:kMerchantId];
      [mParams setValue:[car objectForKey:kCarId defaultValue:nil] forKey:kCarId];
      [mParams setValue:@([Config sharedConfig].user.userId) forKey:kUserId];
      [mParams setValue:@([Config sharedConfig].user.merchantId) forKey:@"shareMerchantId"];
      [mParams setValue:@([Config sharedConfig].user.userId) forKey:@"shareUserId"];
      NSData *data = [NSJSONSerialization dataWithJSONObject:mParams options:0 error:nil];
      NSString *paramString = [[NSString alloc] initWithData:[data base64EncodedDataWithOptions:0] encoding:4];
      
      NSArray *carPics = [car objectForKey:@"carPics" matchClass:[NSArray class] defaultValue:nil];
      CarResourceModel *carModel = [CarResourceModel yy_modelWithJSON:car];
      SCSharePickerVC *sharePickerVC = [[SCSharePickerVC alloc] init];
      sharePickerVC.shareContents = [self contents:carModel];
      sharePickerVC.onlySharePictures  = YES;
      sharePickerVC.car = carModel;
      NSMutableArray *sharedUrls = [NSMutableArray array];
      for (NSDictionary *obj in carPics) {
          if(obj){
            NSString *picUrl = [obj objectForKey:@"picUrl" defaultValue:nil];
            [sharedUrls addObject:sc_url_img(picUrl)];
          }
      }
      
      NSString *url = @"/app/webdetail";
      url = [url stringByAppendingFormat:@"?params=%@",paramString];
      url = sc_url_web(url);
      
      NSString *merchantName = [[Config sharedConfig] merchantNameOfUser];
      NSInteger idx = MIN(sharedUrls.count, 4);
      
      UIFont *font = [UIFont systemFontOfSize:18.];
      CGFloat width = 280.f;
      UIEdgeInsets insets = UIEdgeInsetsMake(24, 57, 24, 57);
      CGFloat interVal = 12.f;
      
      CGSize merchantNameSize = [NSString getSizeWithString:merchantName Font:font maxSize:CGSizeMake(width - insets.left - insets.right, CGFLOAT_MAX)];
      CGSize longPressSize = [NSString getSizeWithString:@"长按查看车辆详情" Font:font maxSize:CGSizeMake(width - insets.left - insets.right, CGFLOAT_MAX)];
      CGFloat hegiht =  insets.top + (merchantNameSize.height>0?(merchantNameSize.height+interVal):0) + (width - insets.left - insets.right)  + (longPressSize.height>0?(longPressSize.height+interVal):0) + 40 + insets.bottom;
      
      [sharedUrls insertObject:[UIImage codeImageWithUrl:url merchantName:merchantName size:CGSizeMake(width, hegiht) longPress:@"长按查看车辆详情"] atIndex:idx];
      sharePickerVC.preShows = sharedUrls;
      [[self getCurrentVC].navigationController pushViewController:sharePickerVC animated:YES];
  });
}

//车辆列表多图分享
RCT_EXPORT_METHOD(sharePlatFormCarListImages:(NSDictionary *)params)
{
    dispatch_async(dispatch_get_main_queue(), ^(){
      NSArray *selectCars = [params objectForKey:@"selectCars" matchClass:[NSArray class] defaultValue:nil];
      NSString *shareOwnerMerchant = [params objectForKey:@"shareOwnerMerchant" defaultValue:nil];
      NSLog(@"shareOwnerMerchant = %@",shareOwnerMerchant);
      SCSharePickerVC *sharePickerVC = [[SCSharePickerVC alloc] init];
      sharePickerVC.onlySharePictures = YES;
            
      NSString *merchantName = [Config sharedConfig].merchantNameOfUser;
      NSString *merchantContact = [NSString stringWithFormat:@"【联系方式】%@ %@",[[NSUserDefaults standardUserDefaults]objectForKey:kUsername],[Config sharedConfig].user.fullname];
      NSString *address = [NSString stringWithFormat:@"【联系地址】%@",[[Config sharedConfig] addressOfUser]];
      if (shareOwnerMerchant.boolValue) {
        sharePickerVC.shareContents = @[[NSString stringWithFormat:@"【诚信车商】%@",merchantName],merchantContact,address];
      }
      

      NSMutableArray *sharedUrls = [NSMutableArray array];
      NSMutableArray *sharedCarIds = [NSMutableArray array];
      [selectCars enumerateObjectsUsingBlock:^(NSDictionary *car, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *mainPic = [car objectForKey:@"mainPic" defaultValue:nil];
        NSString *carId = [car objectForKey:@"carId" defaultValue:nil];
          if(mainPic.length) {
              [sharedUrls addObject:sc_url_img(mainPic)];
          }
          [sharedCarIds addObject:carId];
      }];
      NSInteger count = sharedUrls.count;
      NSInteger idx = MIN(count, 4);
      NSMutableDictionary *param = [NSMutableDictionary dictionary];
      param[kCarIds] = sharedCarIds;
      param[kMerchantId] = @([Config sharedConfig].user.merchantId);
      
      param[kUserId] = [[NSUserDefaults standardUserDefaults] objectForKey:kUserId];
      if (shareOwnerMerchant.boolValue) {//自己的车
        param[@"shareMerchantId"] = @([Config sharedConfig].user.merchantId);
        param[@"shareUserId"] = [[NSUserDefaults standardUserDefaults] objectForKey:kUserId];
      }
      NSString *url = [NSString urlForShareListWithParam:param];
      UIFont *font = [UIFont systemFontOfSize:18.];
      CGFloat width = 280.f;
      UIEdgeInsets insets = UIEdgeInsetsMake(24, 57, 24, 57);
      CGFloat interVal = 12.f;
      WEAKSELF
      CGSize merchantNameSize = [NSString getSizeWithString:shareOwnerMerchant.boolValue ? merchantName:@" " Font:font maxSize:CGSizeMake(width - insets.left - insets.right, CGFLOAT_MAX)];
      CGSize longPressSize = [NSString getSizeWithString:@"长按查看车辆列表" Font:font maxSize:CGSizeMake(width - insets.left - insets.right, CGFLOAT_MAX)];
      CGFloat hegiht =  insets.top + (merchantNameSize.height>0?(merchantNameSize.height+interVal):0) + /*二维码高度*/(width - insets.left - insets.right)  + (longPressSize.height>0?(longPressSize.height+interVal):0) + /*指纹高度*/40 + insets.bottom;
      [sharedUrls insertObject:[UIImage codeImageWithUrl:url merchantName:shareOwnerMerchant.boolValue ? merchantName:@" " size:CGSizeMake(width, hegiht) longPress:@"长按查看车辆列表"] atIndex:idx];
      sharePickerVC.preShows = sharedUrls;
      sharePickerVC.param = param;
      [[self getCurrentVC].navigationController pushViewController:sharePickerVC animated:YES];
  });
}

- (NSArray *)contents:(CarResourceModel *)car{
    NSMutableArray *contents = [[NSMutableArray alloc] init];
    if([car.saleStatus intValue] == CarSaleStatuseOnSale){
        
        NSString *carName = [NSString stringWithFormat:@"【车辆信息】%@%@",car.seriesName,car.speciesName];
        [contents addObject:carName];
      if(car.carType == CarTypeNewCar){
            if(car.markedPrice){
                NSString *markedPrice = [NSString stringWithFormat:@"【车辆价格】%.2f万",[car.markedPrice integerValue]/10000.];
                [contents addObject:markedPrice];
            }
        }else{
            
            if(car.registerDate.length){
                NSArray *dateComponents = [car.registerDate componentsSeparatedByString:@"-"];
                if(dateComponents.count>=2){
                    NSString *registerDate = [NSString stringWithFormat:@"【上牌日期】%@-%@",dateComponents[0],dateComponents[1]];
                    [contents addObject:registerDate];
                }
            }
            
            if(car.mileage){
                NSString *mileage = [NSString stringWithFormat:@"【行驶里程】%.2f万公里",[car.mileage integerValue]/10000.];
                [contents addObject:mileage];
            }
            if(car.markedPrice){
                NSString *markedPrice = [NSString stringWithFormat:@"【车辆价格】%.2f万",[car.markedPrice integerValue]/10000.];
                [contents addObject:markedPrice];
            }
        }
        
        NSString *phone = [NSString stringWithFormat:@"【联系方式】%@",[[NSUserDefaults standardUserDefaults] objectForKey:kUsername]];
        [contents addObject:phone];
        
    }else{
    
        NSString *title = @"销售很给力!!";
        NSString *detail = [NSString stringWithFormat:@"%@-今日已售%@%@",[[Config sharedConfig] merchantNameOfUser],car.seriesName,car.speciesName];
        [contents addObject:title];
        [contents addObject:detail];
    }
    return contents;
}

//企业微信分享
RCT_EXPORT_METHOD(shareToWechatEnt:(NSDictionary *)car)
{
  dispatch_async(dispatch_get_main_queue(), ^(){
    if (![SCAppConfig sharedInstance].wxWorkRegister) {
      [MBProgressHUD showPlainText:@"该账号没有企业微信分享功能!" toView:[self getCurrentVC].view];
      return;
    }
    NSString *title = [car objectForKey:@"title" defaultValue:nil];
    NSString *description = [car objectForKey:@"description" defaultValue:nil];
    NSString *webpageUrl = [car objectForKey:@"webpageUrl" defaultValue:nil];
    NSString *thumbImage = [car objectForKey:@"thumbImage" defaultValue:nil];
    
    
    WWKSendMessageReq *req = [[WWKSendMessageReq alloc] init];
    WWKMessageLinkAttachment *attachment = [[WWKMessageLinkAttachment alloc] init];
    // 示例用链接，请填写你想分享的实际链接的标题、介绍、图标和URL
    attachment.title = title;
    attachment.summary = description;
    attachment.url = webpageUrl;
    attachment.iconurl = thumbImage;
    req.attachment = attachment;
    [WWKApi sendReq:req completionHandler:^(WWKApiResponseErrorCode errorCode){
      NSLog(@"errorCode = %ld",errorCode);
    }];
  });
}

@end
